package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.CRMSqlQuery;
import com.zoho.daliansheng.config.DatasourceEnum;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.utils.CrmApiUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class DispatchListServiceImpl implements DispatchListService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    CRMSqlQuery crmSqlQuery;

    public DispatchListServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig, CRMSqlQuery crmSqlQuery) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
        this.crmSqlQuery = crmSqlQuery;
    }

    @Override
    public void synU8Data(String webServiceUrl, String accountCode, String companyName, List<JSONObject> accountData, List<JSONObject> allUserData,
                          int maxVersion, String versionCrmId, List<JSONObject> batchCurrentStock, int queryMaxVersion) {

        String synModuleName = crmPathConfig.getDispatchModuleName(); // 要同步的模块名称

        // 比较数据
        List<JSONObject> insertList = new ArrayList<>();
        List<JSONObject> updateList = new ArrayList<>();
        List<String> deleteList = new ArrayList<>();

        if (maxVersion == -1) {
            insertList = batchCurrentStock;
        } else {
            for (JSONObject erpData : batchCurrentStock) {
                // sys_change_operation 该字段非常关键,记录了记录的变动类型,I=Insert、U=Update、D=Delete
                String operation = erpData.getString("sys_change_operation");

                String pk_id = erpData.getString("pk_id"); // pk_id

                String selectQuery = crmSqlQuery.getDispatchSqlByPKId(pk_id, companyName);
                List<JSONObject> searchList = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);
                if ("I".equals(operation)) {
                    // 无头表体已经添加过了，所以要修改数据
                    if(searchList.size()>0){
                        JSONObject jsonObject = searchList.get(0);
                        String crmId = jsonObject.getString("id");
                        erpData.put("crmId", crmId);
                        updateList.add(erpData);
                    }else{
                        insertList.add(erpData);
                    }
                } else if ("U".equals(operation)) {
                    if (searchList.size() > 0) {
                        JSONObject jsonObject = searchList.get(0);
                        String crmId = jsonObject.getString("id");
                        erpData.put("crmId", crmId);
                        updateList.add(erpData);
                    }
                } else if ("D".equals(operation)) {

                    //log.info("发货单删除数据：{}", erpData.toJSONString());

                    String pk_selectQuery = crmSqlQuery.getDispatchSqlByPKId(pk_id, companyName);
                    List<JSONObject> searchDelete = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), pk_selectQuery);
                    //log.info("发货单删除searchDelete:{}", JSONObject.toJSONString(searchDelete));
                    if (searchDelete.size() > 0) {
                        JSONObject jsonObject = searchDelete.get(0);
                        String crmId = jsonObject.getString("id");
                        deleteList.add(crmId);
                    }
                }
            }
        }

        // 5 字段映射
        List<JSONObject> crm_insertList = getCrmMappingData(insertList, companyName, accountData, allUserData, "新增");
        List<JSONObject> crm_updateList = getCrmMappingData(updateList, companyName, accountData, allUserData, "修改");
        System.out.println("发货单crm_insertList.size() = " + crm_insertList.size());
        System.out.println("发货单crm_updateList.size() = " + crm_updateList.size());
        System.out.println("发货单deleteList.size() = " + deleteList.size());
        log.info("发货单crm_insertList={}", JSONObject.toJSONString(crm_insertList));
        log.info("发货单crm_updateList={}", JSONObject.toJSONString(crm_updateList));
        log.info("发货单deleteList={}", JSONObject.toJSONString(deleteList));

        // 6 批量操作
        CrmApiUtil.batchInsertDataByList(zohoRecord.getAccessToken(), crm_insertList, synModuleName);
        CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), crm_updateList, synModuleName);
        if (deleteList.size() > 0) {
            CrmApiUtil.batchDeleteModelData(zohoRecord.getAccessToken(), synModuleName, deleteList);
        }

        // 7 最大版本号回传
        if (queryMaxVersion != maxVersion) {
            CrmApiUtil.saveMaxVersion(zohoRecord.getAccessToken(), versionCrmId, queryMaxVersion, crmPathConfig.getMaxVersionModuleName());
        }
    }

    private List<JSONObject> getCrmMappingData(List<JSONObject> erpList, String companyName,
                                               List<JSONObject> accountData, List<JSONObject> allUserData, String operatorType) {

        List<JSONObject> list = new ArrayList<>();
        for (JSONObject erpData : erpList) {

            JSONObject crmData = new JSONObject();
            String crmId = erpData.getString("crmId");
            if (StringUtils.isNotBlank(crmId)) {
                crmData.put("id", crmId);
            }

            crmData.put("KHCompany", companyName); // 所属公司
            crmData.put("erp_id", erpData.getString("dlid")); // 发货单主键
            crmData.put("ERP", erpData.getString("cdlcode")); // 发货单号
            crmData.put("Remark", erpData.getString("cmemo")); // 备注
            crmData.put("SalesType", erpData.getString("cstname")); // 销售类型
            crmData.put("pk_id", erpData.getString("pk_id")); // pk_id
            crmData.put("operator_type", operatorType); // 操作类型

            crmData.put("BusinessType", erpData.getString("cbustype")); // 业务类型

            String csocode = erpData.getString("csocode"); // 订单号
            if (StringUtils.isNotBlank(csocode)) {
                crmData.put("Sales_contract_number", csocode); // 销售合同号
                String selectQuery = crmSqlQuery.getSaleOrderSqlByErpNumber(csocode, companyName);
                List<JSONObject> erp_number = CrmApiUtil.COQLQuery(zohoRecord.getAccessToken(), selectQuery);

                if (erp_number.size() > 0) {
                    String saleOrderId = erp_number.get(0).getString("id");
                    JSONObject temp = new JSONObject();
                    temp.put("id", saleOrderId);
                    crmData.put("order_number", temp); // 订单号
                    crmData.put("OrderDate", erp_number.get(0).getString("OrderDate")); // 订单日期
                    crmData.put("SalesDepartment", erp_number.get(0).getString("SalesDepartment")); // 销售部门
                }
            }
            String ccuscode = erpData.getString("ccuscode");// 客户编码
            if (StringUtils.isNotBlank(ccuscode)) {
                List<JSONObject> erp_account_num = accountData.stream().filter(object ->
                        Objects.nonNull(object.getString("ERP_account_num")) &&
                                object.getString("ERP_account_num").equals(ccuscode) &&
                                (Objects.nonNull(object.getString("KHCompany")) && object.getString("KHCompany").equals(companyName))
                ).collect(Collectors.toList());
                if (erp_account_num.size() > 0) {
                    String saleOrderId = erp_account_num.get(0).getString("id");
                    JSONObject temp = new JSONObject();
                    temp.put("id", saleOrderId);
                    crmData.put("Account_Name", temp); // 客户
                }
            }
            crmData.put("ShippingAddressnew", erpData.getString("cshipaddress")); // 发货地址
            crmData.put("ShuiLv", erpData.getBigDecimal("itaxrate")); // 税率
            crmData.put("PaymentAgreement", erpData.getString("cgatheringplan")); // 收付款协议编码
            crmData.put("PaymentAgreementName", erpData.getString("cgatheringplanname")); // 收付款协议名称

            crmData.put("ShippingMethod", erpData.getString("cscname")); // 发运方式
            crmData.put("BiZhong", erpData.getString("cexch_name")); // 币种

            String cpersoncode = erpData.getString("cpersoncode"); // 业务员编码
            if (StringUtils.isNotBlank(cpersoncode)) {
                JSONObject crmUserCodeByCompany = CrmApiUtil.getCRMUserCodeByCompany(allUserData, cpersoncode, companyName);
                if (Objects.nonNull(crmUserCodeByCompany)) {
                    crmData.put("Salesman", crmUserCodeByCompany); // 业务员
                }
            }
            crmData.put("ShouhuoCompany", erpData.getString("cdeliverunit")); // 收货单位
            crmData.put("ShouhuoContact", erpData.getString("ccontactname")); // 收货联系人
            crmData.put("HuiLv", erpData.getString("iexchrate")); // 汇率
            crmData.put("ShippingDate", erpData.getString("ddate")); // 发货日期
            String dgatheringdate = erpData.getString("dgatheringdate");
            if (StringUtils.isNotBlank(dgatheringdate)) {
                crmData.put("Due_Date", erpData.getString("dgatheringdate").substring(0, 10)); // 到期日
            }

            if (companyName.equals(DatasourceEnum.GONG_CHANG.getCompanyName())) {
                crmData.put("value", erpData.getString("chdefine6")); // 货值

            } else if (companyName.equals(DatasourceEnum.CHANG_ZHOU.getCompanyName())) {
                crmData.put("value", erpData.getString("chdefine21")); // 货值
                crmData.put("ShouHuoAddress", erpData.getString("cdefine13")); // 收货地址
                crmData.put("ShippingRequirements", erpData.getString("ccusdefine7")); // 发货要求
                crmData.put("SpecialShippingRequirements", erpData.getString("cdefine11")); // 特殊发货要求
                crmData.put("Receiving_contact_C", erpData.getString("cdefine10")); // 收货联系人C

            } else if (companyName.equals(DatasourceEnum.DA_LIAN.getCompanyName())) {
                crmData.put("value", erpData.getString("chdefine21")); // 货值
                crmData.put("ShouHuoAddress", erpData.getString("cdefine13")); // 收货地址
                crmData.put("ShippingRequirements", erpData.getString("ccusdefine7")); // 发货要求
                crmData.put("SpecialShippingRequirements", erpData.getString("cdefine11")); // 特殊发货要求
                crmData.put("Receiving_contact_C", erpData.getString("cdefine10")); // 收货联系人C
            } else if (companyName.equals(DatasourceEnum.XIN_CAI_LIAO.getCompanyName())) {
                crmData.put("value", erpData.getString("chdefine21")); // 货值
                crmData.put("ShouHuoAddress", erpData.getString("cdefine13")); // 收货地址
                crmData.put("ShippingRequirements", erpData.getString("ccusdefine7")); // 发货要求
                crmData.put("SpecialShippingRequirements", erpData.getString("cdefine11")); // 特殊发货要求
                crmData.put("Receiving_contact_C", erpData.getString("cdefine10")); // 收货联系人C
            }
            crmData.put("cmaker", erpData.getString("cmaker")); // 制单人
            crmData.put("cverifier", erpData.getString("cverifier")); // 审核人
            crmData.put("ReviewDate", erpData.getString("dverifydate")); // 审核日期

            list.add(crmData);
        }
        return list;
    }

}

